<template>
  <div class="login">
    <!-- 背景装饰元素 -->
    <div class="bg-decoration">
      <div class="floating-shapes">
        <div class="shape shape-1"></div>
        <div class="shape shape-2"></div>
        <div class="shape shape-3"></div>
        <div class="shape shape-4"></div>
        <div class="shape shape-5"></div>
      </div>
    </div>

    <!-- 登录卡片 -->
    <div class="login-card">
      <!-- 卡片头部 -->
      <div class="card-header">
        <div class="logo-container">
          <div class="logo-icon">
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
              <path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
              <path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
            </svg>
          </div>
          <h1 class="logo-text">Admin Dashboard</h1>
        </div>
        <p class="welcome-text">欢迎回来，请登录您的账户</p>
      </div>

      <!-- 登录表单 -->
      <div class="form-container">
        <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          hide-required-asterisk
          status-icon
          size="large"
          class="login-form"
        >
          <el-form-item prop="userName">
            <el-input
              v-model="form.userName"
              :disabled="loading"
              :placeholder="$t('userName')"
              :prefix-icon="User"
              class="form-input"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="form.password"
              type="password"
              :disabled="loading"
              :placeholder="$t('password')"
              :prefix-icon="Lock"
              show-password
              class="form-input"
            />
          </el-form-item>

          <div class="form-options">
            <el-checkbox class="remember-me">记住我</el-checkbox>
            <el-link type="primary" class="forgot-password">忘记密码？</el-link>
          </div>

          <el-button
            type="primary"
            @click="onSubmit.next()"
            class="login-button"
            size="large"
            :loading="loading"
          >
            <span v-if="!loading">{{ $t('login') }}</span>
            <span v-else>登录中...</span>
          </el-button>
        </el-form>
      </div>

      <!-- 卡片底部 -->
      <div class="card-footer">
        <p class="footer-text">还没有账户？ <el-link type="primary">立即注册</el-link></p>
      </div>
    </div>

    <!-- 隐藏的背景图片用于雨滴效果 -->
    <img v-show="false" src="@/assets/imgs/login-bg-1.jpg" ref="bg" style="width: 100%; height: 100%" />
  </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { onMounted, onUnmounted, useTemplateRef, reactive, ref } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
// import { useRouter } from 'vue-router'
import { login } from '@/request/api'
import { setLocal } from '@/lib/utils'
import { throttleTime } from 'rxjs/operators'
import { Subject } from 'rxjs'
// const router = useRouter()
const bg = useTemplateRef('bg')
// const formRef = useTemplateRef('formRef')
const formRef = ref<FormInstance>()
const loading = ref(false)
let RainyDay = (window as any).RainyDay
let engine: any = null
onMounted(() => {
  if (process.env.NODE_ENV === 'development') {
    form.userName = 'admin'
    form.password = '123qwe'
  }
  if (!bg.value) return
  bg.value.onload = () => {
    engine = new RainyDay({
      image: bg.value,
      // parentElement: this.$refs.glass,
      blur: 10,
      opacity: 1, // 定义雨滴的透明度。如果不提供默认为1。
      // crop: [0, 0, 50, 60], //如果只使用图像的某一部分，用此参数提供坐标。如果不提供则默认为整幅图片。
      renderSpeed: 300, // 渲染速度
    })
    engine.rain([[3, 5, 0.5]], 20)
  }
  /**
    // var rainyday = new RainyDay({
    //   image: 'path-to-image.jpg', // 背景图像的路径
    //   blur: 10, // 背景模糊度
    //   opacity: 1, // 背景透明度
    //   gravity: 0.1, // 雨滴重力
    //   frameRate: 30, // 帧率
    //   enableSizeChange: true, // 允许大小变化
    //   dropFrequency: 500, // 雨滴频率
    //   minDropSize: 1, // 最小雨滴大小
    //   maxDropSize: 5, // 最大雨滴大小
    //   renderSpeed: 100, // 渲染速度
    // })
    // rainyday.rain() // 启动雨滴效果

    "rainyday.js" 提供了一些方法来控制雨滴效果的行为：
    rainyday.rain([density])：启动雨滴效果，可选参数 density 用于指定雨滴的密度。
    rainyday.stop()：停止雨滴效果。
    rainyday.pause()：暂停雨滴效果。
    rainyday.resume()：恢复雨滴效果。
 */
})
onUnmounted(() => {
  if (engine) {
    engine.destroy()
    engine = null
    RainyDay = null
  }
})
//
const form = reactive({
  userName: '',
  password: '',
})
const rules = reactive({
  userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})

/* 用rxjs实现一个节流 */
// 创建一个 Subject 来处理 onSubmit 事件
const onSubmit = new Subject<void>()
// 使用 throttleTime 操作符实现节流，这里设置为 1000 毫秒（1秒）
onSubmit.pipe(throttleTime(2000)).subscribe(() => {
  if (!formRef.value) return
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        const { data } = await login(form)
        if (!data.token) {
          ElMessage.error('登录失败，没有获取到token')
          return
        }
        ElMessage.success({
          message: '登录成功',
          type: 'success',
        })
        setLocal('token', data.token)
        setTimeout(() => {
          // 不懂为什么 engine.destroy() 清理不掉，导致cpu使用过高，只能刷新网页
          // if (process.env.NODE_ENV === 'development') {
          //   window.location.href = '/'
          // } else {
          //   window.location.href = '/admin/'
          // }
          window.location.href = import.meta.env.BASE_URL
          loading.value = false
        }, 1000)
      } catch (err) {
        loading.value = false
      }
    }
  })
})
</script>
<style lang="scss" scoped>
.login {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background:
      radial-gradient(circle at 20% 50%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
      radial-gradient(circle at 80% 20%, rgba(255, 119, 198, 0.3) 0%, transparent 50%),
      radial-gradient(circle at 40% 80%, rgba(120, 219, 255, 0.3) 0%, transparent 50%);
    animation: backgroundShift 20s ease-in-out infinite;
  }
}

@keyframes backgroundShift {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.8; }
}

.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.floating-shapes {
  position: relative;
  width: 100%;
  height: 100%;
}

.shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  animation: float 6s ease-in-out infinite;

  &.shape-1 {
    width: 80px;
    height: 80px;
    top: 10%;
    left: 10%;
    animation-delay: 0s;
  }

  &.shape-2 {
    width: 60px;
    height: 60px;
    top: 20%;
    right: 15%;
    animation-delay: 1s;
  }

  &.shape-3 {
    width: 100px;
    height: 100px;
    bottom: 20%;
    left: 15%;
    animation-delay: 2s;
  }

  &.shape-4 {
    width: 40px;
    height: 40px;
    top: 60%;
    right: 20%;
    animation-delay: 3s;
  }

  &.shape-5 {
    width: 70px;
    height: 70px;
    bottom: 10%;
    right: 10%;
    animation-delay: 4s;
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
    opacity: 0.7;
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
    opacity: 1;
  }
}

.login-card {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1000;
  width: 420px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.1),
    0 0 0 1px rgba(255, 255, 255, 0.2);
  padding: 40px;
  animation: cardSlideIn 0.8s ease-out;
  transition: all 0.3s ease;

  &:hover {
    transform: translate(-50%, -50%) translateY(-2px);
    box-shadow:
      0 12px 40px rgba(0, 0, 0, 0.15),
      0 0 0 1px rgba(255, 255, 255, 0.3);
  }
}

@keyframes cardSlideIn {
  from {
    opacity: 0;
    transform: translate(-50%, -50%) translateY(30px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}

.card-header {
  text-align: center;
  margin-bottom: 32px;
}

.logo-container {
  margin-bottom: 16px;
}

.logo-icon {
  width: 48px;
  height: 48px;
  margin: 0 auto 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;

  svg {
    width: 24px;
    height: 24px;
  }
}

.logo-text {
  font-size: 28px;
  font-weight: 700;
  color: #1a202c;
  margin: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.welcome-text {
  color: #64748b;
  font-size: 14px;
  margin: 0;
  font-weight: 400;
}

.form-container {
  margin-bottom: 24px;
}

.login-form {
  .el-form-item {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.form-input {
  :deep(.el-input__wrapper) {
    border-radius: 12px;
    border: 2px solid #e2e8f0;
    box-shadow: none;
    transition: all 0.3s ease;
    background: rgba(248, 250, 252, 0.8);

    &:hover {
      border-color: #cbd5e1;
    }

    &.is-focus {
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
  }

  :deep(.el-input__inner) {
    height: 48px;
    font-size: 15px;
    color: #1a202c;

    &::placeholder {
      color: #94a3b8;
    }
  }

  :deep(.el-input__prefix) {
    color: #64748b;
  }
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.remember-me {
  :deep(.el-checkbox__label) {
    color: #64748b;
    font-size: 14px;
  }
}

.forgot-password {
  font-size: 14px;
  text-decoration: none;

  &:hover {
    text-decoration: underline;
  }
}

.login-button {
  width: 100%;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: left 0.5s;
  }

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);

    &::before {
      left: 100%;
    }
  }

  &:active {
    transform: translateY(0);
  }

  &.is-loading {
    background: linear-gradient(135deg, #94a3b8 0%, #64748b 100%);
  }
}

.card-footer {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #e2e8f0;
}

.footer-text {
  color: #64748b;
  font-size: 14px;
  margin: 0;

  .el-link {
    font-weight: 500;
  }
}

// 响应式设计
@media (max-width: 480px) {
  .login-card {
    width: 90vw;
    max-width: 350px;
    padding: 30px 24px;
  }

  .logo-text {
    font-size: 24px;
  }

  .form-input :deep(.el-input__inner) {
    height: 44px;
  }

  .login-button {
    height: 44px;
  }
}

// 暗色主题适配
@media (prefers-color-scheme: dark) {
  .login {
    background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
  }

  .login-card {
    background: rgba(30, 41, 59, 0.95);
    color: #f1f5f9;
  }

  .logo-text {
    color: #f1f5f9;
  }

  .welcome-text {
    color: #94a3b8;
  }

  .form-input :deep(.el-input__wrapper) {
    background: rgba(51, 65, 85, 0.8);
    border-color: #475569;

    &.is-focus {
      border-color: #667eea;
    }
  }

  .form-input :deep(.el-input__inner) {
    color: #f1f5f9;

    &::placeholder {
      color: #64748b;
    }
  }

  .card-footer {
    border-top-color: #475569;
  }

  .footer-text {
    color: #94a3b8;
  }
}
</style>
